#include"BirdThrower.h"
#include"Box2D/Box2D.h"
#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"Graviation.h"
#include"Tool.h"
#include<cmath>
using namespace std;

BirdThrower::BirdThrower(Graviation * app, b2Body * bird, const b2Vec2& shootPoint)
{
	this->app = app;
	this->bird = bird;
	this->shootPoint = b2Vec2(shootPoint.x*PTM_RADIO, shootPoint.y*PTM_RADIO);
	
	bird->SetTransform(this->shootPoint, bird->GetAngle());

	pryBar = LSYEasyBody::createBox(b2Vec2(shootPoint.x, 5), b2Vec2(20, 5), b2BodyType::b2_kinematicBody);
	b2PolygonShape* shape = new b2PolygonShape;
	b2Vec2 center(0, this->shootPoint.y*0.5);
	shape->SetAsBox(5 * PTM_RADIO, this->shootPoint.y*0.5, center, 0);
	pryBar->CreateFixture(shape, 1);
	b2MassData* md = new b2MassData;
	pryBar->GetMassData(md);
	md->center.Set(0, (-shootPoint.y + 5)*PTM_RADIO);
	md->I = md->mass*md->center.LengthSquared() + 20;
	pryBar->SetMassData(md);
	REALSE_NULL(shape);
	REALSE_NULL(md);
}

BirdThrower::~BirdThrower()
{
}

void BirdThrower::onMouseDown(const b2Vec2 & pos)
{
    startPos = b2Vec2(pos.x*PTM_RADIO, pos.y*PTM_RADIO);
	b2Fixture* fd = pryBar->GetFixtureList();
	do
	{
		if (fd->GetShape()->TestPoint(pryBar->GetTransform(), startPos))
		{
			isTouch = true;
		}
		fd = fd->GetNext();
	} while (fd->GetNext());
}

void BirdThrower::onMouseUp(const b2Vec2 & pos)
{
	isTouch = false;
	bird->SetLinearVelocity(b2Vec2(200 * PTM_RADIO, 0));
	resetAngle();
}

void BirdThrower::onMouseMove(const b2Vec2 & pos)
{
	if (isTouch)
	{
		b2Vec2 start = pryBar->GetPosition();
		b2Vec2 target(pos.x*PTM_RADIO, pos.y*PTM_RADIO);
		float angle = LSYEasyWorld::calcAngle(start, target);
		pryBar->SetTransform(pryBar->GetPosition(), -angle);
	}
}

void BirdThrower::resetAngle()
{
	
}

void BirdThrower::resetWork()
{
	while (true)
	{
		if (abs(pryBar->GetAngle()) < PI / 18)
		{
			pryBar->SetAngularVelocity(0);
			pryBar->SetTransform(pryBar->GetPosition(), 0);
		}
	}
}

